﻿using System;
using System.Net;
using System.Reflection;
using System.Web;
using log4net;

namespace GrailTechnology.AutoTags.Providers
{
    public class TagTheNetService : ITagProvider
    {
        private static readonly ILog Log_ = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private const string ServiceUrlFormat = @"http://tagthe.net/api/?text={0}&view=json";

        public string[] GenerateTags(string content)
        {
            try
            {
                var client = new WebClient();

                if (Proxy != null)
                {
                    client.Proxy = Proxy;
                }

                var response = client.DownloadString(string.Format(ServiceUrlFormat, HttpUtility.UrlEncode(content)));
                if (string.IsNullOrEmpty(response))
                {
                    return new string[0];
                }

                return response.ToTagTheNetReponse().ToStringArray();
            }
            catch (Exception ex)
            {
                Log_.Fatal(ex);
                throw;
            }
        }

        public WebProxy Proxy { get; set; }
    }
}
